package token

import (
	"encoding/base64"
	"encoding/json"
	"github.com/mitchellh/cli"
	"my-go-cli/utils"
	"time"
)

// EncodeCommand 结构
type EncodeCommand struct{}

// Help 帮助
func (e *EncodeCommand) Help() string {
	return "对原始信息进行加密处理"
}

// Run 运行
func (e *EncodeCommand) Run(args []string) int {
	if len(args) != 1 {
		println("请输入待加密的字符串！")
		return 2
	}
	raw := output{
		Code:    0,
		Msg:     "",
		Time:    time.Now().Unix(),
		Payload: args[0],
	}
	rb, err := json.Marshal(raw)
	if err != nil {
		printErr(err, 1)
		return 2
	}
	s, err := encrypt(rb, aesKey)
	if err != nil {
		printErr(err, 2)
		return 2
	}
	printOk(s)
	return 1
}

// Synopsis 显示概要
func (e *EncodeCommand) Synopsis() string {
	return "对原始信息进行加密处理"
}

// EncodeCommandFactory 工厂
func EncodeCommandFactory() (cli.Command, error) {
	return new(EncodeCommand), nil
}

func encrypt(rawData, key []byte) (string, error) {
	data, err := utils.AesCBCEncrypt(rawData, key)
	if err != nil {
		return "", err
	}
	return base64.RawURLEncoding.EncodeToString(data), nil
}
